﻿using DG.Tweening;
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class CrossStageView : MonoBehaviour
{
    [SerializeField] private GameObject _textContext;
    [SerializeField] private Image _textMesk;
    [SerializeField] private Image _bgImg;

    [SerializeField] private Text _stageIndexText;
    [SerializeField] private Text _restIndexText;
    private int _stageIndex;
    private int _restCount;
    public void Load(int stageIndex,int restCount)
    {
        _stageIndex = stageIndex;
        _restCount = restCount;
        _stageIndexText.text = stageIndex.ToString();
        _restIndexText.text = restCount.ToString();
        ShowBG();
    }

    [SerializeField]private float _fadeInValue;
    [SerializeField]private float _fadeInTime;
    

    [SerializeField] private float _fadeWaitTime;

    [SerializeField] private float _fadeOutValue;
    [SerializeField] private float _fadeOutTime;

    private bool _active;
    private void ShowBG()
    {
        _active = false;
        //StartCoroutine(LoadSceneAsync());

        Sequence sequence = DOTween.Sequence();
        sequence.Append(_bgImg.DOFade(1, _fadeInValue).OnComplete(() => {
            _textContext.SetActive(true);
        }));
        sequence.AppendInterval(_fadeInTime);

        sequence.Append(_textMesk.DOFade(0, _fadeInValue));

        sequence.AppendInterval(_fadeWaitTime);

        sequence.Append(_textMesk.DOFade(1, _fadeOutValue).OnComplete(() => {
            _textContext.SetActive(false);
            _active = true;
            StartGame();
            StartCoroutine(LoadSceneAsync());
        }));
     
        sequence.Play();
    }


    private IEnumerator LoadSceneAsync() 
    {
        AsyncOperation operation=SceneManager.LoadSceneAsync(_stageIndex);
        operation.allowSceneActivation = false;
        while (!operation.isDone) 
        {
            if (_active) 
            {
                operation.allowSceneActivation = true;
                break;
            }
            yield return null;
        }
    }
    private void StartGame()
    {
        //GameManager.Instance.LoadScene();
        StartCoroutine(LoadScenAsync());
    }

    private IEnumerator LoadScenAsync()
    {
        yield return SceneManager.LoadSceneAsync(_stageIndex);
        GameSystem.Instance.ChangeGameState(State.Running);
    }
}
